import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Divider, Table, message, Card, Icon, Alert} from 'antd';
import {TABLE, PAGINATION_OPTIONS, PAGE, COMMON_TABLE_EMPTY_TEXT, COMMON_TABLE_QUERY_FAIL_TEXT} from '../constants';
import TextInput from 'Shared/components/TextInput';
import WrappedTag from '../common/WrappedTag';
import CategoryTree from '../common/CategoryTree';
import styles from './style.css';
import {formatMessage} from '../common/localize';
import {injectIntl} from './intl';
import {uniqBy} from 'lodash';
import {getObjById, getPathById, getTreeData, computeSelectedRows} from './utils';
const FormItem = Form.Item;
const EMPTY_ARRAY = [];

const FORM_OPTIONS_COL = {
    xxl: 12,
    xl: 12,
};

const FORM_OPTIONS_ITEM = {
    labelCol: {
        xxl: {span: 5},
        xl: {span: 7},
        sm: {span: 8},
        lg: {span: 8}
    },
    wrapperCol: {
        xxl: {span: 19},
        xl: {span: 17},
        sm: {span: 8},
        lg: {span: 16}
    },
    colon: true
};
class DealerSelectPanel extends PureComponent {
    state = {
        // 总代
        condition: {
            pageIndex: PAGE.index,
            pageSize: PAGE.smallSize,
        },
        selectedRowKeys: [],
        selectedRows: [],
        currentCondition: {},
        keys: EMPTY_ARRAY,
        rows: EMPTY_ARRAY,
        loading: false,
        data: EMPTY_ARRAY,
        total: 0,
        error: false,

        // 大区树
        trees: EMPTY_ARRAY,
        treeId: '',
        isFetching: false,
        treeError: false,

    };

    componentDidMount() {
        this.handleRefreshRegions();
    }

    handleRefreshRegions = () => {
        this.setState({
            isFetching: true,
            trees: EMPTY_ARRAY
        });
        return this.props.getRegions().then(res => this.setState({
            treeError: !res.ok,
            isFetching: false,
            treeId: '',
            trees: res.ok ? res.data.content : EMPTY_ARRAY
        }));
    }

    handleConditionChange = (value, name) => this.setState({condition: Object.assign({}, this.state.condition, {[name]: value})});

    handleQueryBtnClick = () => this.onQuery(Object.assign({}, this.state.currentCondition, this.state.condition, {pageIndex: PAGE.index}));

    handleFilterPressEnter = (value, name) => this.setState(() => ({condition: Object.assign({}, this.state.condition, {[name]: value})}), this.handleQueryBtnClick);

    handleTableChange = (pagination, filters, sorter) => {
        const query = {
            sortField: null,
            isDesc: null
        };
        if(pagination.pageSize)
            query.pageSize = pagination.pageSize;
        if(pagination.current)
            query.pageIndex = pagination.current - 1;
        if(sorter.order && sorter.field) {
            query.sortField = sorter.field;
            query.isDesc = sorter.order === 'descend';
        }
        this.onQuery(Object.assign({}, this.state.currentCondition, query));
    };

    isSortOrder = propName => this.state.currentCondition.sortField === propName && (this.state.currentCondition.isDesc ? 'descend' : 'ascend');

    onQuery = conditions => {
        const {isLeaf = false} = getObjById(this.state.trees, this.state.treeId);
        this.setState({loading: true});
        this.props.getDealers(Object.assign(conditions, this.props.conditions, {
            treeId: this.state.treeId,
            isParentNode: !isLeaf
        })).then(result => this.setState({
            loading: false,
            error: result.ok,
            data: result.ok ? result.data.content : EMPTY_ARRAY,
            total: result.ok ? result.data.totalElements : 0,
            currentCondition: conditions
        }));
    };

    onSelectChange = (keys, rows) => this.setState({
        keys,
        rows: uniqBy(this.state.rows.concat(rows), 'id').filter(row => keys.includes(row.id))
    });

    onClear = () => this.setState({
        keys: [],
        rows: []
    });

    onCloseTag = id => this.setState({
        keys: this.state.keys.filter(key => key !== id),
        rows: this.state.rows.filter(row => row.id !== id),
    });

    onSelect = () => {
        if(!this.state.selectedRows.length)
            return message.warn(formatMessage({
                id: 'dealerSelectPanel.validMessage1',
                defaultMessage: '请选择总代'
            }));
        this.props.onSelect(this.state.selectedRows);
    };

    onSelectCategory = id => {
        this.setState({
            treeId: id
        }, this.handleQueryBtnClick);
    }

    onCloseTreeTag = () => {
        this.setState({
            treeId: ''
        }, this.handleQueryBtnClick);
    }

    onLoadData = record => {
        this.setState({
            isFetching: true,
        });
        const {id, name} = record;
        return this.props.getMarketDepartments({
            areaName: name
        }).then(res => {
            if(res.ok) {
                const path = getPathById(this.state.trees, id);
                const data = getTreeData(this.state.trees, res.data.content, path);
                this.setState({
                    isFetching: false,
                    trees: data
                });
            } else
                this.setState({
                    isFetching: false,
                    treeError: true
                });
            return res.ok;
        });
    }
    onDelete= id => {
        const keys = this.state.selectedRowKeys.filter(k => k !== id);
        const rows = this.state.selectedRows.filter(r => r.id !== id);
        this.setState({
            selectedRowKeys: [...keys],
            selectedRows: [...rows]
        });
    }
    onClearAll=() => {
        this.setState({
            selectedRowKeys: [],
            selectedRows: []
        });
    }
    render() {
        const columns = [{
            title: formatMessage({
                id: 'dealerSelectPanel.code',
                defaultMessage: '编号'
            }),
            dataIndex: 'code',
            sorter: true,
            sortOrder: this.isSortOrder('code')
        }, {
            title: formatMessage({
                id: 'dealerSelectPanel.name',
                defaultMessage: '名称'
            }),
            sorter: true,
            dataIndex: 'name',
            sortOrder: this.isSortOrder('name')
        },
        {
            title: formatMessage({
                id: 'dealerSelectPanel.shortCode',
                defaultMessage: '简码',
            }),
            dataIndex: 'shortCode',
            sortOrder: this.isSortOrder('shortCode')
        },
        {
            title: formatMessage({
                id: 'dealerSelectPanel.shortName',
                defaultMessage: '简称',
            }),
            dataIndex: 'shortName',
            sortOrder: this.isSortOrder('shortName')
        },
        {
            title: formatMessage({
                id: 'dealerSelectPanel.countryName',
                defaultMessage: '国家',
            }),
            dataIndex: 'countryName',
            sortOrder: this.isSortOrder('countryName')
        },
        {
            title: formatMessage({
                id: 'dealerSelectPanel.provinceName',
                defaultMessage: '城市',
            }),
            dataIndex: 'provinceName',
            sortOrder: this.isSortOrder('provinceName')
        },
        {
            title: formatMessage({
                id: 'dealerSelectPanel.cityName',
                defaultMessage: '地址',
            }),
            dataIndex: 'cityName',
            sortOrder: this.isSortOrder('cityName')
        }].concat(this.props.columns.map(col => {
            if(col.sorter)
                col.sortOrder = this.isSortOrder(col.dataIndex);
            return col;
        }));

        const pagination = {
            total: this.state.total,
            current: this.state.currentCondition.pageIndex + 1,
            pageSize: this.state.currentCondition.pageSize,
            ...PAGINATION_OPTIONS
        };

        const onRow = this.props.multi ? null : record => ({onDoubleClick: () => this.props.onSelect(record)});

        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                const rows = computeSelectedRows(this.state.selectedRowKeys, this.state.selectedRows, selectedRowKeys, selectedRows);
                this.setState({
                    selectedRowKeys,
                    selectedRows: rows
                });
            }
        };

        const alertMessage = (
            <div>
                <span>
                    {formatMessage({
                        id: 'partSelectPanel.alertMessage.span',
                        defaultMessage: '已选择'
                    })}
                    <a onClick={this.toggleShowTags}>
                        {this.state.selectedRows.length}
                        {formatMessage({
                            id: 'partSelectPanel.alertMessage.a.number',
                            defaultMessage: '项'
                        })}
                    </a>
                    {formatMessage({
                        id: 'partSelectPanel.alertMessage.comma',
                        defaultMessage: '，'
                    })}
                    <a onClick={this.onClearAll} className={styles.clearAllTag}>
                        {formatMessage({
                            id: 'partSelectPanel.alertMessage.deleteAll',
                            defaultMessage: '清除选择'
                        })}
                    </a>
                    <Button
                        size="small"
                        type="primary"
                        className={styles.partBtn}
                        onClick={this.onSelect}>
                        {formatMessage({
                            id: 'partSelectPanel.btn.confirm',
                            defaultMessage: '确认'
                        })}
                    </Button>
                </span>
                {this.state.showTags && (
                    <div style={{
                        marginTop: '8px'
                    }}>
                        {this.state.selectedRows.map(r => (
                            <WrappedTag key={r.id} closable id={r.id} onClose={this.onDelete}>
                                {r.name}
                            </WrappedTag>
                        ))}
                    </div>
                )}
            </div>
        );
        const {name: treeName} = getObjById(this.state.trees, this.state.treeId);
        return (
            <div>
                <Row gutter={8}>
                    <Col md={10} xl={8} xxl={6} >
                        <Card>
                            <div className={styles.mainTree}>
                                {this.state.treeError ? <span>{formatMessage({
                                    id: 'dealerSelectPanel.treeError.message',
                                    defaultMessage: '点击右侧按钮刷新'
                                })}{'   '}<Icon className={styles.blue} onClick={this.handleRefreshRegions} type="reload" /></span> : null}
                                <CategoryTree loading={this.state.loading}
                                    pages={this.state.trees}
                                    locatedKey={this.state.treeId}
                                    onLoadData={this.onLoadData}
                                    onSelect={this.onSelectCategory} />
                            </div>
                        </Card>
                    </Col>
                    <Col md={14} xl={16} xxl={18}>
                        <Card>
                            <Row className="form-standard">
                                <Col {...FORM_OPTIONS_COL}>
                                    <FormItem label={formatMessage({
                                        id: 'dealerSelectPanel.code',
                                        defaultMessage: '编号'
                                    })} {...FORM_OPTIONS_ITEM}>
                                        <TextInput name="code" value={this.state.condition.code}
                                            onPressEnter={this.handleFilterPressEnter}
                                            onBlur={this.handleConditionChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS_COL}>
                                    <FormItem label={formatMessage({
                                        id: 'dealerSelectPanel.name',
                                        defaultMessage: '名称'
                                    })} {...FORM_OPTIONS_ITEM}>
                                        <TextInput name="name" value={this.state.condition.name}
                                            onPressEnter={this.handleFilterPressEnter}
                                            onBlur={this.handleConditionChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS_COL}>
                                    <FormItem label={formatMessage({
                                        id: 'dealerSelectPanel.shortCode',
                                        defaultMessage: '简码'
                                    })} {...FORM_OPTIONS_ITEM}>
                                        <TextInput name="shortCode" value={this.state.condition.shortCode}
                                            onPressEnter={this.handleFilterPressEnter}
                                            onBlur={this.handleConditionChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS_COL}>
                                    <FormItem label={formatMessage({
                                        id: 'dealerSelectPanel.shortName',
                                        defaultMessage: '简称'
                                    })} {...FORM_OPTIONS_ITEM}>
                                        <TextInput name="shortName" value={this.state.condition.shortName}
                                            onPressEnter={this.handleFilterPressEnter}
                                            onBlur={this.handleConditionChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col className={styles['inline-button']}>
                                    {/* <FormItem key="btn" {...FORM_OPTIONS_ITEM}> */}
                                    <Button type="primary" loading={this.state.loading} onClick={this.handleQueryBtnClick}>{formatMessage({
                                        id: 'dealerSelectPanel.query',
                                        defaultMessage: '查询'
                                    })}</Button>
                                    {treeName && <WrappedTag className={styles.tagFontSize} color="blue"
                                        closable onClose={this.onCloseTreeTag}>{treeName}</WrappedTag>}
                                    {/* </FormItem> */}
                                </Col>
                            </Row>
                            <Divider className={styles.divider} />
                            <Alert className={styles.alert} type="info" message={alertMessage} showIcon/>
                            <Table
                                className="white-space-nowrap"
                                rowKey="id"
                                dataSource={this.state.data}
                                columns={columns}
                                onRow={onRow}
                                rowSelection={rowSelection}
                                loading={this.state.loading}
                                pagination={pagination}
                                onChange={this.handleTableChange}
                                rowClassName={styles.tableCursor}
                                {...TABLE}
                                locale={{emptyText: this.state.error ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT}} />
                        </Card>
                    </Col>
                </Row>
                
            </div>
        );
    }
}


import * as api from './api';

const EMPTY_OBJECT = {};

DealerSelectPanel.defaultProps = {
    multi: false,
    isRequired: false,
    getDealers: api.getDealers,
    conditions: EMPTY_OBJECT,
    columns: EMPTY_ARRAY
};

DealerSelectPanel.propTypes = {
    /**
     * 选中后回调，return multi ? object : array
     */
    onSelect: PropTypes.func.isRequired,
    /**
     * 多选，default false
     */
    columns: PropTypes.array,
    /**
     * 查询总代API，为空取默认API
     */
    conditions: PropTypes.object,
    /**
     * 增加默认查询条件，界面不做展示
     */
    getDealers: PropTypes.func,
    /**
     * 确认时是否允许为空
     */
    isRequired: PropTypes.bool,
    /**
     * 增加展示列，antd column
     */
    multi: PropTypes.bool,
};

export default injectIntl(DealerSelectPanel);
